<template>
  <div class="page-container">
    <div class="control-container">
      <div class="right-panel">
        <div class="search-panel">
          <el-form :inline="true" label-width="100">
            <el-form-item label="开始时间">
              <el-date-picker
                v-model="query.startTime"
                type="date"
                placeholder="请选择开始时间"
                value-format="yyyy-MM-dd HH:mm:ss"
              />
            </el-form-item>
            <el-form-item label="结束时间">
              <el-date-picker
                v-model="query.endTime"
                type="date"
                placeholder="请选择结束时间"
                value-format="yyyy-MM-dd 23:59:59"
              />
            </el-form-item>
            <el-form-item label="任务名称">
              <el-input v-model="query.taskName" />
            </el-form-item>
            <el-form-item v-if="roleType === 'e036_03' || roleType === 'e036_02' || roleType === 'e036_01'" label="责任人">
              <el-input v-model="query.responsible" />
            </el-form-item>

            <el-form-item label="任务类型">
              <el-select v-model="query.taskType" class="w-100" placeholder="请输入类型">
                <el-option
                  v-for="(item,index) in taskTypes"
                  :key="index+'task_type'"
                  :value="item.code"
                  :label="item.codeName"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="任务状态">
              <el-select v-model="query.taskStatus" multiple style="width: 220px" placeholder="请输入状态">
                <el-option
                  v-for="(item,index) in taskStatus"
                  :key="index+'task_status'"
                  :value="item.code"
                  :label="item.codeName"
                />
              </el-select>
            </el-form-item>
            <div style="float: right;">
              <el-button type="primary" @click="handleSelect">查询</el-button>
              <el-button type="primary" @click="resetForm()">重置</el-button>
              <el-button v-if="hasBth('task:add')" type="primary" @click="handleAddOrDetail('add')">添加</el-button>
              <el-button v-if="hasBth('task:review')" type="primary" @click="handleBatchReview()">批量审核</el-button>
              <el-button v-if="hasBth('task:batchUrge')" type="primary" @click="handleBatchUrge()">批量催办</el-button>
              <el-button v-if="hasBth('task:revoke')" type="primary" @click="handleRevoke()">撤销</el-button>
              <el-button v-if="hasBth('task:report')" :loading="exportLoading" type="primary" @click="downLoadTask">导出</el-button>
            </div>

          </el-form>
        </div>

        <div class="">
          <el-table
            v-loading="tableLoading"
            class="grid-data-table"
            height="calc(100vh - 400px)"
            :data="tableData"
            @selection-change="handleSelectionChange"
          >
            <el-table-column align="center" type="selection" width="60" />
            <el-table-column prop="num" label="任务编号" show-overflow-tooltip>
              <template slot-scope="scope">
                <div style="color:#0004ff;cursor:pointer;" @click="taskDetails(scope.row)">{{ scope.row.num }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="taskName" label="任务名称" />
            <el-table-column prop="taskContent" label="任务内容" width="250" show-overflow-tooltip />
            <el-table-column prop="projectDepartmentName" label="项目部" />
            <el-table-column prop="publisherName" label="发布人" />
            <el-table-column prop="responsibleName" label="责任人" />
            <el-table-column prop="processPersonnelName" label="协助人" show-overflow-tooltip />
            <el-table-column prop="taskType" label="任务类型">
              <template slot-scope="scope">{{ getDictLabel('e008', scope.row.taskType) }}</template>
            </el-table-column>
            <el-table-column prop="startTime" label="开始时间">
              <template slot-scope="scope">
                <div>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="completionTime" label="完成时间">
              <template slot-scope="scope">
                <div>{{ parseTime(scope.row.completionTime, '{y}-{m}-{d}') }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="taskStatus" label="状态">
              <template slot-scope="scope">{{ getDictLabel('e009', scope.row.taskStatus) }}
              </template>
            </el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button v-if="(scope.row.taskStatus === 'e009_00' || scope.row.taskStatus === 'e009_01' )&& hasBth('task:report')" class="table-inner-btn" type="primary" size="mini" @click="handleAddOrDetail('detail',scope.row)">处理</el-button>
                <el-button v-else-if="scope.row.taskStatus === 'e009_02' && hasBth('task:review') " class="table-inner-btn" type="primary" size="mini" @click="handleAddOrDetail('detail',scope.row)">审核</el-button>
                <el-button v-else class="table-inner-btn" type="primary" size="mini" @click="handleAddOrDetail('detail',scope.row)">详情</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination-container">
            <Pagination
              v-show="query.total>0"
              :total="query.total"
              :page.sync="query.page"
              :limit.sync="query.limit"
              @pagination="initData"
            />
          </div>
        </div>
      </div>
    </div>
    <AddTaskDialog
      :dialog-visible="dialogVisible"
      :dialog-type="dialogType"
      :obj="obj"
      @closeDialog="closeDialog"
      @flushPage="flushPage"
    />
    <BatchHandle
      :batch-handle-dialog-visible="batchHandleDialogVisible"
      :dialog-type="dialogType"
      :ids="ids"
      :task-list="taskList"
      @closeDialog="closeDialog"
      @flushPage="flushPage"
    />
    <Detail
      :dialog-visible-test="dialogVisibleTest"
      :obj="obj"
      @closeDialog="closeDialog"
      @flushPage="flushPage"
    />
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'
import { getDict } from '@/utils/dict'
import { hasBtnPermission as hasBth, getRoleType } from '@/utils/buttons'
import { download, getPage as getTaskPage, revoke, batchUrge, read } from '@/api/info/task'
import { downloadFile, getDictLabel, parseTime } from '@/utils'
import AddTaskDialog from '@/views/task/components/AddTaskDialog'
import BatchHandle from '@/views/task/components/BatchHandle'
import Detail from '@/views/task/components/Detail'

export default {
  name: 'TaskList',
  components: {
    BatchHandle,
    AddTaskDialog,
    Pagination,
    Detail
  },
  data() {
    return {
      exportLoading: false,
      tableLoading: false,
      query: {
        page: 1, limit: 10, total: 0,
        startTime: null, endTime: null, responsible: null,
        taskStatus: [], taskType: 'e008_01', taskName: null, id: null
      },
      tableData: [],
      dialogVisible: false,
      reportDialogVisible: false,
      batchHandleDialogVisible: false,
      batchHandleDialog: false,
      dialogVisibleTest: false,
      dialogType: 'detail',
      taskTypes: [],
      taskStatus: [],
      obj: null,
      ids: [],
      taskStatusList: [],
      taskTypeList: [],
      roleType: null,
      taskList: [],
      userId: ''
    }
  },
  mounted() {
  },
  created() {
    this.query.id = this.$route.query.id
    this.taskTypes = getDict('e008')
    this.taskStatus = getDict('e009')
    this.roleType = this.getRoleType()
    if (this.roleType === 'e036_03') {
      this.query.taskStatus = ['e009_00', 'e009_01', 'e009_02']
    } else if (this.roleType === 'e036_04') {
      this.query.taskStatus = ['e009_00', 'e009_01']
    }
    const info = this.$store.getters.user.info
    if (info) {
      let obj = info
      if (typeof info === 'string') {
        obj = JSON.parse(info)
      }
      this.userId = obj.id
    }
    this.initData()
  },
  methods: {
    getDictLabel, parseTime, hasBth, getRoleType,
    initData() {
      const query = JSON.parse(JSON.stringify(this.query))
      if (this.query.taskStatus.length > 0) {
        query.taskStatus = this.query.taskStatus.join(',')
      }
      if (this.query.taskType === 'e008_01') {
        query.taskType = null
      }
      this.tableLoading = true
      getTaskPage(query).then(result => {
        this.tableLoading = false
        this.query.total = result.data.total
        this.tableData = result.data.list
        this.tableLoading = false
        this.query.id = null
      }).catch(() => {
        this.query.id = null
        this.tableLoading = false
      })
    },
    // 导出任务
    downLoadTask() {
      this.exportLoading = true
      const query = JSON.parse(JSON.stringify(this.query))
      if (this.query.taskStatus.length > 0) {
        query.taskStatus = this.query.taskStatus.join(',')
      }
      if (this.query.taskType === 'e008_01') {
        query.taskType = null
      }
      download(query).then(result => {
        downloadFile(result, '任务列表', 'xlsx')
        this.exportLoading = false
      }).catch(() => {
        this.exportLoading = false
      })
    },
    // 批量审核
    handleBatchReview() {
      if (this.ids.length < 1) {
        this.$message({
          message: '请至少选择一条待审核任务',
          type: 'warning'
        })
        return
      }
      if (this.unique(this.taskTypeList).length > 1) {
        this.$message({
          message: '选中的任务类型不一致',
          type: 'warning'
        })
        return
      }
      for (let i = 0; i < this.taskStatusList.length; i++) {
        if (this.taskStatusList[i] !== 'e009_02') {
          this.$message({
            message: '选中的任务状态不一致/不正确',
            type: 'warning'
          })
          return
        }
      }
      this.batchHandleDialogVisible = true
      this.dialogType = 'batchHandle'
    },
    // 批量催办
    handleBatchUrge() {
      if (this.ids.length < 1) {
        this.$message({
          message: '请至少选择一条待处理任务',
          type: 'warning'
        })
        return
      }
      for (let i = 0; i < this.taskStatusList.length; i++) {
        if (this.taskStatusList[i] !== 'e009_01') {
          this.$message({
            message: '选中的任务状态不一致/不正确',
            type: 'warning'
          })
          return
        }
      }
      batchUrge(this.ids[0]).then(() => {
        this.$message.success('成功')
        this.flushPage()
      }).catch(() => {
      })
    },
    // 撤销
    handleRevoke() {
      if (this.ids.length < 1) {
        this.$message({
          message: '请选择要撤销的任务',
          type: 'warning'
        })
        return
      }
      if (this.ids.length > 1) {
        this.$message({
          message: '只能同时撤销一条任务信息',
          type: 'warning'
        })
        return
      }
      if (this.taskStatusList[0] === 'e009_03' || this.taskStatusList[0] === 'e009_04') {
        this.$message({
          message: '该任务已审核完成，不能撤销',
          type: 'warning'
        })
        return
      }
      if (this.taskStatusList[0] === 'e009_05') {
        this.$message({
          message: '该任务已撤销',
          type: 'warning'
        })
        return
      }
      this.$confirm('确认撤销选中的任务吗?', '提示', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        revoke(this.ids[0]).then(() => {
          this.$message.success('成功')
          this.flushPage()
        }).catch(() => {
        })
      })
    },
    // 多选赋值
    handleSelectionChange(val) {
      this.ids = []
      this.taskStatusList = []
      this.taskTypeList = []
      val.forEach(item => {
        this.ids.push(item.id)
        this.taskStatusList.push(item.taskStatus)
        this.taskTypeList.push(item.taskType)
      })
      this.taskList = val
    },
    // 字符串去重
    unique(arr) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr) && res.set(arr, 1))
    },
    resetForm() {
      if (this.roleType === 'e036_03') {
        this.query.taskStatus = ['e009_01', 'e009_02']
      } else if (this.roleType === 'e036_04') {
        this.query.taskStatus = ['e009_01']
      }
      this.query = {
        ...this.query,
        startTime: null, endTime: null, responsible: null,
        taskType: 'e008_01', taskName: null
      }
    },
    // 查询
    handleSelect() {
      this.query.page = 1
      this.initData()
    },
    // 添加
    handleAddOrDetail(dialogType, row) {
      // 把未读的且操作人是责任人的标记为已读 即变成待处理状态   把未读的当做未处理
      if (row != null && row.taskStatus === 'e009_00' && row.responsibleId === this.userId) {
        read({ id: row.id })
        row.taskStatus = 'e009_01'
      }

      this.dialogVisible = true
      this.dialogType = dialogType
      this.obj = row
    },
    taskDetails(row) {
      //  把未读的且操作人是责任人的标记为已读 即变成待处理状态
      if (row != null && row.taskStatus === 'e009_00' && row.responsibleId === this.userId) {
        read({ id: row.id })
        row.taskStatus = 'e009_01'
      }

      this.dialogVisibleTest = true
      this.obj = row
    },
    // 任务上报
    handleReport(row) {
      this.reportDialogVisible = true
      this.obj = row
    },
    flushPage() {
      this.clearQuery()
      this.initData()
    },
    clearQuery() {
      this.query = {
        ...this.query,
        page: 1, limit: 10, total: 0,
        startTime: null, endTime: null, responsible: null,
        taskType: 'e008_01', taskName: null
      }
    },
    closeDialog() {
      this.dialogVisible = false
      this.reportDialogVisible = false
      this.batchHandleDialogVisible = false
      this.dialogVisibleTest = false
      this.batchHandleDialog = false
      this.initData()
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
